package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.permission;

import com.alibaba.fastjson.JSON;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.RolesLevel;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.permission.*;
import com.cqhilink.iot.jobstandardmanagement.services.redisservice.RedisClientTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huangxueqian on 2017/1/6/006.
 * 权限设置问题，
 * 请参考权限设置数据
 */

public class JsmPermissionServiceImpl implements JsmPermissionService {
    @Autowired
    JsmRolesMenuService rolesMenuService;
    @Autowired
    private JsmAccountRoleService accountRoleService;
    @Autowired
    private JsmRolesService rolesService;
    @Autowired
    private JsmMenuService menuService;
    @Autowired(required = false)
    private RedisClientTemplate redisClientTemplate ;
    @Autowired(required = false)
    private JsmRoleMenuButtonService roleMenuButtonService ;

    @Override
    public List<Menu> getFirstNavPermission(String systemCode, EmployeeVo employeeVo,String pfToken) throws Exception {
        boolean isAdmin = false;
        String menusStr = redisClientTemplate.get(pfToken + systemCode +"FirstNavPermission") ;
        List<Menu> resMenus = new ArrayList<>();
        if(StringUtils.isEmpty(menusStr)){
            List<AccountRole> accountRoles = accountRoleService.getRolesByAccount(systemCode, employeeVo);
        /* 根据role获取菜单 */
        /* 判读是否是系统管理员 ，如果是系统管理员则查询该系统的一级菜单 */
            isAdmin = this.isAdmin(accountRoles);
            List<RoleMenu> roleMenus = rolesMenuService.getMenuByRole(accountRoles, systemCode);
            resMenus = menuService.getFirstLevelMenu(systemCode, roleMenus, isAdmin);
            redisClientTemplate.set(pfToken + systemCode +"FirstNavPermission",JSON.toJSONString(resMenus)) ;
        }else{
            resMenus = JSON.parseArray(menusStr,Menu.class);
        }
        return resMenus;

    }

    /**
     * @param menuId     根据一级菜单ID， 获取对应菜单权限
     * @param employeeVo 当前用户信息
     * @param systemCode 系统编码
     * @return
     * @throws Exception
     */
    @Override
    public List<Menu> getLeftMenuNavPermission(String systemCode,EmployeeVo employeeVo, String menuId,String pfToken) throws Exception {
        List<Menu> resMenu = new ArrayList<>();
        /* 1、获取当前用户的角色；2：获取当前用户角色的菜单*/
        /* 1、获取一级菜单的子菜单 */
        /*判断是否是系统管理员*/
        String menusStr = redisClientTemplate.get(pfToken + systemCode +"LeftMenuNavPermission"+menuId) ;
        if(StringUtils.isEmpty(menusStr)){
            boolean isAdmin = false ;
            List<AccountRole> accountRoles = accountRoleService.getRolesByAccount(systemCode, employeeVo);
        /* 根据role获取菜单 */
        /* 判读是否是系统管理员，如果是系统管理员则查询该系统的一级菜单 */
            isAdmin = this.isAdmin(accountRoles);
            resMenu = menuService.getAfterLevelMenu(systemCode, menuId, employeeVo, isAdmin);
            if(resMenu != null && resMenu.size() > 0 ){
                redisClientTemplate.set(pfToken + systemCode +"LeftMenuNavPermission"+menuId,JSON.toJSONString(resMenu)) ;
            }
        }else {
            resMenu = JSON.parseArray(menusStr,Menu.class);
        }
        return resMenu ;
    }

    /**
     * @param systemCode 根据系统
     * @param employeeVo 当前登录人员
     * 查询当前人员该子系统的所有菜单
     */
    @Override
    public List<Menu> getAllMenuPermission(String pfToken,String systemCode, EmployeeVo employeeVo) throws Exception {
        List<Menu> resMenus =  new ArrayList<>();
        String menusStr = redisClientTemplate.get(pfToken  +"AllMenuPermission") ;
        if(org.apache.commons.lang.StringUtils.isEmpty(menusStr)){
            // getAllMenuPermission(systemCode,employeeVo)
            resMenus = menuService.getAllMenuPermission(systemCode,employeeVo);
            if(resMenus!=null && resMenus.size() > 0){
                redisClientTemplate.set(pfToken+"AllMenuPermission",JSON.toJSONString(resMenus));
            }
        }else{
            resMenus =  JSON.parseArray(menusStr,Menu.class) ;
        }
        return resMenus ;
    }

    private boolean isAdmin(List<AccountRole> accountRoles) {
        boolean isAdmin = false;
        if (accountRoles != null) {
            for (AccountRole accountRole : accountRoles) {
                Roles roles = null;
                try {
                    roles = rolesService.rolesSelect(accountRole.getRoleId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (roles != null && roles.getRoleType().intValue() == RolesLevel.ROLES_S.getCode()) {
                    isAdmin = true; // 判断是系统管理员
                }
            }
        }
        return isAdmin;
    }


    /**
     * @param btnCode 按钮唯一标识
     * @param menuId  按钮所属菜单
     * @param employeeVo 当前处理人是否存在该按钮
     */
    @Override
    public boolean isBtnPermission(String btnCode, String menuId, EmployeeVo employeeVo) throws Exception {
         boolean isPermission =  false ;
         Map<String,MenuButton> reMap = new HashMap<>();
        List<MenuButton>   roleMenuButtonList = roleMenuButtonService.queryBtnByLoginEmployeeVo(employeeVo);
        if(roleMenuButtonList != null && roleMenuButtonList.size() > 0){
            for(MenuButton menuButton :roleMenuButtonList){
                reMap.put(menuButton.getButtonCode(),menuButton) ;
            }
        }

        if(!StringUtils.isEmpty(reMap.get(btnCode))){
            isPermission = true ;
        }
        return isPermission ;
    }

    /**
     * @param requestUrl
     * @param employeeVo
     */
    @Override
    public boolean isBtnPermission(String requestUrl,String pfToken,String systemCode, EmployeeVo employeeVo) throws Exception {
        requestUrl = requestUrl.substring(1,requestUrl.length());
        boolean isRest = false ;
        Map<String,String> resMap = new HashMap<>();
        List<Menu> systemAllByEmployeeList = this.getAllMenuPermission(pfToken,null,employeeVo);
        if(systemAllByEmployeeList!=null && systemAllByEmployeeList.size() > 0){
                for(Menu menu :systemAllByEmployeeList){
                    if(org.apache.commons.lang.StringUtils.isNotEmpty(menu.getUrl())){
                        resMap.put(menu.getUrl(),menu.getUrl());
                    }
                }
        }
        List<MenuButton>   roleMenuButtonList = roleMenuButtonService.queryBtnByLoginEmployeeVo(employeeVo);
        if(roleMenuButtonList != null && roleMenuButtonList.size() > 0){
            for(MenuButton menuButton :roleMenuButtonList){
                resMap.put(menuButton.getButtonUrl(),menuButton.getButtonUrl()) ;
            }
        }
        // 根据路径 取出对应的值
        if(org.apache.commons.lang.StringUtils.isNotEmpty(resMap.get(requestUrl))){
            isRest = true ;
        }
        // 根据路径 取出对应的值 将nositemesh 的路径转成  sitemesh 路径
        if(org.apache.commons.lang.StringUtils.isNotEmpty(resMap.get(requestUrl.replace("nositemesh","sitemesh")))){
            isRest = true ;
        }
        return isRest;
    }


    /**
     * @param menuName 菜单名称
     * @param systemId 菜单系统Code
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> authFavoritesMenu(String menuName, String systemId,EmployeeVo employeeVo) throws Exception {
        Map<String, Object> autoMap = menuService.authMenu(menuName,systemId,employeeVo) ;
        return autoMap ;
    }
}
